#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "sdlshowbmpthread.h"

#include <SDL2/SDL.h>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_pushButton_clicked()
{
//    SDLShowBMPThread* sdlShowBMPThread = new SDLShowBMPThread(this);

//    sdlShowBMPThread->start();

    SDL_Surface* surface = nullptr;
    SDL_Window* window = nullptr;
    SDL_Renderer* renderer= nullptr;
    SDL_Texture * texture = nullptr;
    SDL_Event event;
    const char* bmp_path = "/Users/apple/Documents/ffmpeg/qt/image/demo.bmp";

    int res = SDL_Init(SDL_INIT_VIDEO);

    if(res) {

        qDebug() << "SDL_Init fail" << SDL_GetError();
        goto end;
    }

   surface = SDL_LoadBMP(bmp_path);

   if(!surface) {

       qDebug() << bmp_path << " load error";
       goto end;
   }

//   qDebug() << surface->w;

   window = SDL_CreateWindow("bmp显示",SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,surface->w,surface->h,SDL_WINDOW_SHOWN);

   if(!window) {

       qDebug() << "SDL_CreateWindow";
       goto end;
   }

   renderer = SDL_CreateRenderer(window,-1,SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);

   if(!renderer) {

       renderer = SDL_CreateRenderer(window,-1,SDL_RENDERER_SOFTWARE);
   }

   if(!renderer) {

       qDebug() << "SDL_CreateRenderer error";
       goto end;
   }

   texture = SDL_CreateTextureFromSurface(renderer,surface);

   if(!texture) {

       qDebug() << "SDL_CreateTextureFromSurface error";
       goto end;
   }

   res = SDL_SetRenderDrawColor(renderer,255,0,0,SDL_ALPHA_OPAQUE);

   if(res) {

       qDebug() << "SDL_SetRenderDrawColor error";
       goto end;
   }

   res = SDL_RenderClear(renderer);

   if(res) {

       qDebug() << "SDL_SetRenderDrawColor error";
       goto end;
   }

   res = SDL_RenderCopy(renderer,texture,nullptr,nullptr);

   if(res) {

       qDebug() << "SDL_RenderCopy";
       goto end;
   }

   SDL_RenderPresent(renderer);

   qDebug() << "2222";

   while (true) {

       res = SDL_WaitEvent(&event);

       qDebug() << event.type;
       if(event.type == SDL_QUIT){

           break;
       }
   }
end:

   SDL_DestroyTexture(texture);
   SDL_DestroyRenderer(renderer);
   SDL_DestroyWindow(window);
   SDL_Quit();
}
